define([
  "UtilDir/util",
  "UtilDir/tool",
  "UtilDir/dialog",
  "UtilDir/searchBlock",
  "static/app/fwsjcj/preport/getPcReport",
  "EasyUI", "EasyUI-lang"
], function (Util, Tool, Dialog, SearchBlock, Report) {

  var sysPath = getServer() + "/static/app/fwsjcj";

  var zwFormHtml = sysPath + "/brick/views/zwForm.html";
  var getZwController = function () {
    return getServer() + "/platform/org/zws/";
  };

  /**
   * 页面初始化
   */
  var init = function () {
    initSearchBlock();
    queryBtnBind();
    createProvince();
    $('input[name="queryType"][value="0"]').attr('checked', true);
  };

  var initSearchBlock = function () {
    SearchBlock.init("searchBlock");
  };

  var queryBtnBind = function () {
    $('input[type=radio][name=queryType]').change(function () {
      // 获取input radio选中值，方法一
      //var myvalue = $('input:radio[name="queryType"]:checked').val();
      // 获取input radio选中值，方法二
      var myvalue = $(this).val();
      if (myvalue == 0) {
        $("#chooseTask").attr('disabled', true).css({'backgroundColor': 'gray'});
        $("#province").combobox({disabled: false});
        $("#city").combobox({disabled: false});
        $("#county").combobox({disabled: false});
        $('#taskName').prop('disabled', true);
        $('#taskName').val('');
      } else {
        $("#chooseTask").attr('disabled', false).css({'backgroundColor': '#007fff'});
        $('#taskName').prop('disabled', false);
        $("#province").combobox({disabled: true});
        $("#city").combobox({disabled: true});
        $("#county").combobox({disabled: true});
        $('#province').combobox('clear');
        $('#city').combobox('loadData', {});//清空option选项
        $('#city').combobox('clear');
        $('#county').combobox('loadData', {});//清空option选项
        $('#county').combobox('clear');
      }
    });
    var search_loading = Util.loading({
      text: '正在加载'
    })
    //查询
    $("#btnSearch").click(function () {
      search_loading.show();
      SearchData(search_loading);
    });
    //重置
    $("#btnReset").click(function () {
      $('#province').combobox('clear');
      $('#city').combobox('loadData', {});//清空option选项
      $('#city').combobox('clear');
      $('#county').combobox('loadData', {});//清空option选项
      $('#county').combobox('clear');
      $('#taskName').val('');
    });
    // 导出报告
    $("#exportReport").click(function () {
      // if ($('#preports-contents').css('display') == 'none') {
      //   Util.alert('请先查询报告');
      // } else {
      //   exportPC();
      // }
      exportPC();
    });
    $("#chooseTask").click(function () {
      chooseTask();
    })
  };

  // 选择任务
  var chooseTask = function () {
    var buttons = [];
    buttons.push({
      name: '确定',
      callback: function () {
        //点击确定
        $("#taskName").val($("#TaskGrid").datagrid("getChecked").map(item => item.taskName).join(','))
        $("#chooseTask").html('查看');
        dialog.hide();
      }
    });
    var dialog = Dialog({
      id: "viewTaskDialog",
      cache: false,
      title: '请选择',
      width: "1000px",
      height: "600px",
      body: '<form id="searchForm">\n' +
        '       <div class="row">\n' +
        '          <div class="col-md-4 form-horizontal">\n' +
        '              <div class="form-group">\n' +
        '                 <label for="searchTaskName" class="col-md-4 control-label"> </span>任务名称:</label>\n' +
        '                 <div class="col-md-8">\n' +
        '                    <input id="searchTaskName" type="text" name="searchTaskName" class="form-control">' +
        '                 </div>\n' +
        '              </div>\n' +
        '           </div>' +
        '           <button id="btnTaskSearch" class="btn btn-default" type="button">查询</button>\n' +
        '           <button id="btnTaskReset" class="btn btn-default" type="button">重置</button>' +
        '      </div>' +
        '</form>' +
        '<div id="TaskGrid" idField="taskId"></div>',
      buttons: buttons,
      afterOpen: function () {
        getTaskList();
        $("#btnTaskSearch").click(getTaskList);
        $("#btnTaskReset").click(function () {
          $('#searchTaskName').val('');
          getTaskList()
        });
      }
    });
    dialog.show();
  }

  var getTaskList = function () {
    $("#TaskGrid").datagrid({
      url: getServer() + "/fw/task/page/0",
      method: "GET",
      nowrap: false,
      columns: [[
        {field: "ck", checkbox: true},
        {field: 'taskNum', title: '任务编号', width: '15%', align: 'center'},
        {
          field: 'taskName', title: '任务名称', width: '21.4%', align: 'center',
          formatter: function (value, rowData, rowIndex) {
            return '<a href="#" onclick="_view(\'' + rowData.taskId + '\',\'' + rowData.groupId + '\',\'' + rowData.taskName + '\',\'' + rowData.status + '\');"> ' + rowData.taskName + ' </a> '
          }
        },
        {field: 'division', title: '任务地区', width: '13%', align: 'center'},
        {field: 'taskManager', title: '任务管理员', width: '9%', align: 'center'},
        {field: 'groupName', title: '承担小组', width: '15%', align: 'center'},
        {field: 'groupLeader', title: '组长', width: '8%', align: 'center'},
        {field: 'groupLeaderMobile', title: '手机号码', width: '10%', align: 'center'},
        {
          field: 'status', title: '任务状态', width: '8%', align: 'center',
          formatter: function (value, rowData, rowIndex) {
            if (value == '0') {
              return '未分配';
            } else if (value == '1') {
              return '进行中';
            } else if (value == '2') {
              return '已完成';
            }
          }
        }
      ]],
      queryParams: {
        taskName: $("#searchTaskName").val()
      },
      pagination: true,
      pageSize: 10,
      onLoadSuccess: function (data) {
        for (var i = 0; i < data.rows.length; i++) {
          if ($("#taskName").val().includes(data.rows[i].taskName)) {
            $('#TaskGrid').datagrid('checkRow', i);
          }
        }
      }
    });
  }

  // 查看任务详情
  var TaskFormHtml = sysPath + "/sifttaskmanage/views/taskForm.html";
  var TaskFormHtmlReadOnly = sysPath + "/sifttaskmanage/views/taskFormReadOnly.html";
  var getTask = function (id) {
    $.ajax({
      url: getServer() + "/fw/task/" + id,
      type: "get",
      success: function (data) {
        Tool.deserialize("taskForm", data);
      }
    });
  };
  window._view = function (taskId, groupId, taskName, status) {
    var taskFormHtml = '';
    if (status == "0") {
      taskFormHtml = TaskFormHtml;
    } else {
      taskFormHtml = TaskFormHtmlReadOnly;
    }
    var slidebar = Util.slidebar({
      url: taskFormHtml,
      width: "580px",
      cache: false,
      close: true,
      afterLoad: function () {
        getTask(taskId);
        //查看队员列表
        $("#viewteamBtn").bind("click", function () {
          var buttons = [];
          buttons.push({
            name: '确定',
            callback: function () {
              //点击确定
              dialog.hide();
            }
          });
          var dialog = Dialog({
            id: "viewTeamDialog",
            cache: false,
            title: '队员情况', //dialog标题
            width: "1000px",
            height: "550px",
            body: '<div id="TeamGrid"></div>',
            buttons: buttons,
            afterOpen: function () {
              $("#TeamGrid").datagrid({
                url: getServer() + "/fw/group/" + groupId,
                method: "GET",
                height: "515px",
                fitColumns: true,
                nowrap: false,
                autoRowHeight: false,
                singleSelect: true,
                columns: [[
                  {field: 'relName', title: '姓名', width: '18%', align: 'center'},
                  {field: 'idNumber', title: '身份证号', width: '28%', align: 'center'},
                  {field: 'mobilePhone', title: '手机号', width: '23%', align: 'center'},
                  {field: 'groupZW', title: '队内职务', width: '15%', align: 'center'},
                  {field: 'formNum', title: '完成表单数量', width: '18%', align: 'center'},
                  /*{field: 'operation', title: '操作', width: '17%', align: 'center',
                      formatter: function (value, rowData, rowIndex) {
                      debugger;
                          return '<a onclick="_viewTrajectory(\'' + rowData.userId+ '\',\'' + taskId+ '\',\'' +taskName+ '\',\'' +rowData.relName+ '\')">查看队员轨迹</a >';
                      }
                  },*/
                ]],

                pagination: false,
                pageSize: 10
              });
            }
          });
          dialog.show();
          window._viewTrajectory = function (userId, taskId, taskName, userName) {
            debugger;
            dialog.hide();
            slidebar.close();
            $('#myTab a[href="#replayMap"]').tab('show');
            //replayInitAll();
            startReplayData(userId, taskId, taskName, userName);
          }
        });
      }
    });
  };

  var SearchData = function (search_loading, cb) {
    var proValue = $('#province').combobox('getText');
    var cityValue = $('#city').combobox('getText');
    var areaValue = $('#county').combobox('getText');
    var taskNameValue = $('#taskName').val();
    var searchValue = {
      belongtoProvince: '',
      belongtoCity: '',
      belongtoArea: '',
      taskName: ''
    }
    searchValue.taskName = taskNameValue;
    if (proValue) {
      // if (cityValue == "全部" || cityValue == '北京市' || cityValue == '天津市' || cityValue == '上海市' || cityValue == '重庆市') {
      if (cityValue == "全部") {
        cityValue = '';
      }
      searchValue.belongtoProvince = proValue;
      searchValue.belongtoCity = cityValue;
      searchValue.belongtoArea = areaValue;
    }
    Report.timeStamp = Util.getCurrentLoginUser()['user'].userId+new Date().getTime()
    $.ajax({
      url: getServer() + "/fw/pcReport/analysisExport",
      contentType: "application/json",
      method: "GET",
      data: searchValue,
      success: function (data) {
        search_loading.close();
        $('#preports-tips').hide();
        $('#preports-contents').show();
        //工作区建筑物总数统计图(栋数)
        Report.createBarEcharts({
          id: 'buildingWorkspace1',
          x: data.buildingNumColumn.x,
          title: "栋数",
          subtitle: '总栋数（栋）：'+data.buildingNumColumn.y.reduce((prev, cur) => prev+cur, 0),
          yname: '个数',
          data: data.buildingNumColumn.y
        });
        //工作区建筑物总数统计图(面积)
        Report.createBarEcharts({
          id: 'buildingWorkspace2',
          x: data.buildingAreaColumn.x,
          title: "面积",
          subtitle: '总面积（平方米）：'+data.buildingAreaColumn.y.reduce((prev, cur) => prev+cur, 0).toFixed(2),
          yname: '平方米',
          data: data.buildingAreaColumn.y

        });
        //城镇房屋结构类型占比统计图
        renderPie({id: 'cityBuildingsArea', data: data.buildingCityAreaDataByStructureType, name: '面积'});
        renderPie({id: 'cityBuildingsNum', data: data.buildingCityNumDataByStructureType, name: '栋数'});
        //农村房屋结构类型占比统计图
        renderPie({id: 'ruralBuildingsArea', data: data.buildingVillageAreaDataByStructureType, name: '面积'});
        renderPie({id: 'ruralBuildingsNum', data: data.buildingVillageNumDataByStructureType, name: '栋数'});
        //城镇住宅建造年代占比统计图
        renderPie({id: 'cityBuildingsAgeArea', data: data.buildingAreaCityByBuildingTime, name: '面积'});
        renderPie({id: 'cityBuildingsAgeNum', data: data.buildingNumCityByBuildingTime, name: '栋数'});
        //城镇房屋设施（非住宅）建造年代占比统计图
        renderPie({id: 'ucityBuildingsAgeArea', data: data.buildingAreaNocityeByBuildingTime, name: '面积'});
        renderPie({id: 'ucityBuildingsAgeNum', data: data.buildingNumNoCityByBuildingTime, name: '栋数'});
        //农村住房建造年代占比统计图
        renderPie({id: 'ruralBuildingsAgeArea', data: data.buildingAreaVillageByBuildingTime, name: '面积'});
        renderPie({id: 'ruralBuildingsAgeNum', data: data.buildingNumVillageByBuildingTime, name: '栋数'});
        //农村公共建筑建造年代占比统计图
        renderPie({id: 'pbruralBuildingsAgeArea', data: data.buildingAreaVillagePubByBuildingTime, name: '面积'});
        renderPie({id: 'pbruralBuildingsAgeNum', data: data.buildingNumVillagePubByBuildingTime, name: '栋数'});
        //城镇住宅抗震设防烈度占比统计图
        renderPie({id: 'cityEarthquakeArea', data: data.buildingAreaCityByFortificationIntensity, name: '面积'});
        renderPie({id: 'cityEarthquakeNum', data: data.buildingNumCityByFortificationIntensity, name: '栋数'});
        //城镇房屋设施（非住宅）抗震设防烈度占比统计图
        renderPie({id: 'ucityEarthquakeArea', data: data.buildingAreaNoCityByFortificationIntensity, name: '面积'});
        renderPie({id: 'ucityEarthquakeNum', data: data.buildingNumNoCityByFortificationIntensity, name: '栋数'});
        //农村住房抗震设防烈度占比统计图
        renderPie({id: 'ruralEarthquakeArea', data: data.buildingAreaVillageByFortificationIntensity, name: '面积'});
        renderPie({id: 'ruralEarthquakeNum', data: data.buildingNumVillageByFortificationIntensity, name: '栋数'});
        //农村公共建筑抗震设防烈度占比统计图
        renderPie({id: 'pbruralEarthquakeArea', data: data.buildingAreaVillageByFortificationIntensity, name: '面积'});
        renderPie({id: 'pbruralEarthquakeNum', data: data.buildingAreaVillageByFortificationIntensity, name: '栋数'});
        //农村居住房屋抗震构造措施占比统计图
        renderPie({id: 'ruralStructureArea', data: data.buildingAreaVillageByHouseMeasures, name: '面积'});
        renderPie({id: 'ruralStructureNum', data: data.buildingNumVillageByHouseMeasures, name: '栋数'});
        //农村居住房屋曾受灾情况占比统计图
        renderPie({id: 'pbruralDisastersArea', data: data.buildingAreaVillageByOnceAffected, name: '面积'});
        renderPie({id: 'pbruralDisastersNum', data: data.buildingNumVillageByOnceAffected, name: '栋数'});
        //城镇住宅抗震设防情况占比统计图
        renderPie({id: 'citySituationArea', data: data.buildingAreaCityByResult, name: '面积'});
        renderPie({id: 'citySituationNum', data: data.buildingNumCityByResult, name: '栋数'});
        //城镇房屋设施（非住宅）抗震设防情况占比统计图
        renderPie({id: 'ucitySituationArea', data: data.buildingAreaNoCityByResult, name: '面积'});
        renderPie({id: 'ucitySituationNum', data: data.buildingNumNoCityByResult, name: '栋数'});
        //农村住房抗震设防情况占比统计图
        renderPie({id: 'ruralSituationArea', data: data.buildingAreaVillageByResult, name: '面积'});
        renderPie({id: 'ruralSituationNum', data: data.buildingNumVillageByResult, name: '栋数'});
        //农村公共建筑抗震设防情况占比统计图
        renderPie({id: 'pbruralSituationArea', data: data.buildingAreaVillagePubByResult, name: '面积'});
        renderPie({id: 'pbruralSituationNum', data: data.buildingNumVillagePubByResult, name: '栋数'});
        //城镇住宅安全隐患占比统计图
        renderPie({id: 'cityhiddenDangerArea', data: data.buildingAreaCityByBuildingIsDamage, name: '面积'});
        renderPie({id: 'cityhiddenDangerNum', data: data.buildingNumCityByBuildingIsDamage, name: '栋数'});
        //城镇房屋设施（非住宅）安全隐患占比统计图
        renderPie({id: 'ucityhiddenDangerArea', data: data.buildingAreaNoCityByBuildingIsDamage, name: '面积'});
        renderPie({id: 'ucityhiddenDangerNum', data: data.buildingNumNoCityByBuildingIsDamage, name: '栋数'});
        //农村住房安全隐患占比统计图
        renderPie({id: 'ruralhiddenDangerArea', data: data.buildingAreaVillageByBuildingIsDamage, name: '面积'});
        renderPie({id: 'ruralhiddenDangerNum', data: data.buildingNumVillageByBuildingIsDamage, name: '栋数'});
        //农村公共建筑安全隐患占比统计图
        renderPie({id: 'pbruralhiddenDangerArea', data: data.buildingAreaVillagePubByBuildingIsDamage, name: '面积'});
        renderPie({id: 'pbruralhiddenDangerNum', data: data.buildingNumVillagePubByBuildingIsDamage, name: '栋数'});
        cb && cb()
      }
    });
  }
  var renderPie = function (config) {
    Report.createPieEcharts({
      id: config.id,
      title: config.title,
      subtitle: config.subtitle,
      series: {
        name: config.name,
        data: config.data
      }
    });
  }
  // 导出报告
  var exportPC = function () {
    var proValue = $('#province').combobox('getText');
    var cityValue = $('#city').combobox('getText');
    var areaValue = $('#county').combobox('getText');
    var taskNameValue = $('#taskName').val();
    var searchValue = {
      province: '',
      city: '',
      area: '',
      taskName: ''
    }
    searchValue.taskName = taskNameValue;

    if (proValue) {
      // if (cityValue == "全部" || cityValue == '北京市' || cityValue == '天津市' || cityValue == '上海市' || cityValue == '重庆市') {
      if (cityValue == "全部") {
        cityValue = '';
      }
      searchValue.province = proValue;
      searchValue.city = cityValue;
      searchValue.area = areaValue;
    }
    // Util.alert('正在导出报告，请关注浏览器的下载内容！')
    // window.location.href = getServer() + '/fw/pcReport/exportReport?province=' + searchValue.province + '&city=' + searchValue.city + '&area=' + searchValue.area + '&taskName=' + searchValue.taskName + '&timeStamp=' + Report.timeStamp;

    var search_loading = Util.loading({
      text: '正在导出报告'
    })
    search_loading.show();
    SearchData(search_loading, function(){
      Util.alert('正在导出报告，请关注浏览器的下载内容！')
      window.location.href = getServer() + '/fw/pcReport/exportReport?province=' + searchValue.province + '&city=' + searchValue.city + '&area=' + searchValue.area + '&taskName=' + searchValue.taskName + '&timeStamp=' + Report.timeStamp;
    })

//      $.ajax({
//          url: getServer() + '/fw/pcReport/exportReport',
//          contentType: "application/json",
//          method: "GET",
//          data: searchValue,
//          success: function (data) {
//              Util.alert('导出成功！');
//          }
//      })
  }
  var createProvince = function () {
    $('#province').combobox({
      url: "/app/divisions/root/subdivisions",
      method: 'get',
      editable: false, //不可编辑状态  
      cache: false,
      // panelHeight: 'auto',//自动高度适合  
      valueField: 'divisionId',
      textField: 'divisionName',
      onLoadSuccess: function (data) {
        $('#province').combobox('select', '');
      }
    });
    $("#province").combobox({
      onSelect: function (value) {
        var re = value.divisionId;
        var list = new Array();
        list.push({
          "divisionId": "-1",
          "divisionName": ""
        });
        if (re != null && re != '') {
          list.push(re);
        }

        if (value.divisionName == '北京市' || value.divisionName == '天津市' || value.divisionName == '上海市' || value.divisionName == '重庆市') {
          var division = [];
          division.push(value);
          $('#city').combobox('loadData', division);
          $('#city').combobox('select', value.divisionName);

          $('#county').combobox({
            url: "/app/divisions/" + value.divisionId + "/subdivisions",
            method: 'get',
            editable: false, //不可编辑状态  
            cache: false,
            //panelHeight: 'auto',//自动高度适合  
            valueField: 'divisionId',
            textField: 'divisionName',
            onLoadSuccess: function () {
              $('#county').combobox('select', list[0].divisionName);
            }
          });
        } else {
          $('#city').combobox({
            url: "/app/divisions/" + value.divisionId + "/subdivisions",
            method: 'get',
            editable: false, //不可编辑状态  
            cache: false,
            // panelHeight: 'auto',//自动高度适合  
            valueField: 'divisionId',
            textField: 'divisionName',
            onLoadSuccess: function () {
              $('#city').combobox('select', list[0].divisionName);
            }
          });
          createCity();
          $('#county').combobox('loadData', {}); //清空option选项
          $('#county').combobox('clear');
        }
      }
    });

    createCity();
    $('#county').combobox({
      data: '',
      editable: false, //不可编辑状态  
      cache: false
    });
  }

  var createCity = function () {
    $("#city").combobox({
      onSelect: function (value) {
        var re = value.divisionId;
        var list = new Array();
        list.push({
          "divisionId": "-1",
          "divisionName": ""
        });
        if (re.list != null && re.list != 'null') {
          list.push(re);
        }
        $('#county').combobox({
          url: "/app/divisions/" + value.divisionId + "/subdivisions",
          method: 'get',
          editable: false, //不可编辑状态  
          cache: false,
          //panelHeight: 'auto',//自动高度适合  
          valueField: 'divisionId',
          textField: 'divisionName',
          onLoadSuccess: function () {
            $('#county').combobox('select', list[0].divisionName);
          }
        });
      }
    });
  }


  return {
    init: init
  };
});